package com.yubest.junit.robot;

import lombok.Getter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 按键机器人帮助类
 *
 * @Author: hweiyu
 * @Date: 2022/11/1 17:43
 */
public class RobotHolder {

    @Getter
    private Robot robot;

    public RobotHolder() {
        try {
            robot = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    public void keyPress(int ... keys) {
        for (int key : keys) {
            robot.keyPress(key);
            robot.delay(10);
        }
        for (int key : keys) {
            robot.keyRelease(key);
        }
    }

    public void delay(int ms){
        robot.delay(ms);
    }

    public void mouseLeftPress(int x,int y){
        mousePress(x, y, InputEvent.BUTTON1_MASK);
    }

    public void mouseRightPress(int x,int y){
        mousePress(x, y, InputEvent.BUTTON3_MASK);
    }

    public void mousePress(int x, int y, int buttons){
        robot.mouseMove(x, y);
        robot.delay(10);
        robot.mousePress(buttons);
        robot.delay(20);
        robot.mouseRelease(buttons);
    }

    public byte[] screenCapture(int xStart, int yStart, int xEnd, int yEnd) throws IOException {
        BufferedImage image = robot.createScreenCapture(new Rectangle(xStart, yStart, xEnd-xStart,yEnd-yStart));
        try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", os);
            return os.toByteArray();
        }
    }
}
